package com.qunar.crawler.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
    private static String url;
    private static String driver;
    private static String user;
    private static String password;
    private static String interval;

    static {
        Properties props = new Properties();
        try {
            props.load(new FileInputStream("jdbc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            driver = props.getProperty("driver");
            url = props.getProperty("url");
            user = props.getProperty("user");
            password = props.getProperty("password");
            interval = props.getProperty("interval");
        } catch (Exception e1) {
            System.out.println("属性文件异常");
            e1.printStackTrace();
        }

        System.out.println(driver);
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    // 返回抓取间隔(暂时写在这里)
    public static String getInterval() {
        return interval;
    }

    // 返回Connection
    public static Connection getConnection() {
        try {
            Connection con = DriverManager.getConnection(url, user, password);
            return con;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void release(Connection connection, PreparedStatement pstmt, ResultSet rs) {
        try {
            if (rs != null)
                rs.close();
            if (pstmt != null)
                pstmt.close();
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
